<?php

class Marjory_Service_ResponseWriter_XML implements Marjory_Service_ResponseWriter_Interface {
    protected $results;
    protected $fieldsToInclude = array();
    
    /**
     * @param array $fieldNames Array of fields to include in the response
     */
    public function includeFields(Array $fieldNames)
    {
        $this->fieldsToInclude = $fieldNames;
    }
    
    /**
     * @param array $results Array of Marjory_Document objects
     */
    public function setResponse(Marjory_Service_ResultProxy $results)
    {
        $this->results = $results;
    }
    

    
    public function getResponseObject()
    {
        $xml = simplexml_load_string('<response />');
        $xml->addChild('responseHeader')->addChild('status', 0);
        $xmlResults = $xml->addChild('result');
        $xmlResults->addAttribute('numFound', $this->results->numResults);
        
        foreach($this->results as $key => $doc) {
            Marjory_Service::getLog()->log("Iterating over result $key ...", Zend_Log::DEBUG);
            /* @var $doc Marjory_Document */
            $xmlDoc = $xmlResults->addChild('doc');
            $xmlDoc->addAttribute('score', $doc->getScore());
            $xmlDoc->addAttribute('uri', htmlspecialchars($doc->getURI()));
            foreach($doc->getFieldNames() as $fieldName) {
                if (empty($this->fieldsToInclude) || in_array($fieldName, $this->fieldsToInclude)) {
                    $xmlDoc->addChild('str', htmlspecialchars($doc->getField($fieldName)))
                           ->addAttribute('name', htmlspecialchars($fieldName));
                }
            }
        }
        
        return $xml;
    }
    
    /**
     * Returns the response string in the desired format
     * @return string
     */
    public function __toString()
    {
        return $this->getResponseObject()->asXML();
    }
}

/*
 ?xml version="1.0" encoding="UTF-8"?>
<response>
  <responseHeader>
    <status>0</status><QTime>1</QTime>
  </responseHeader>

  <result numFound="2" start="0">
   <doc>
    <str name="id">MA147LL/A</str>
    <str name="name">Apple 60 GB iPod Black</str>
   </doc>
   <doc>
    <str name="id">EN7800GTX/2DHTV/256M</str>
    <str name="name">ASUS Extreme N7800GTX</str>
   </doc>
  </result>
</response>
*/